//
//  ViewController.swift
//  DiffableDataSource
//
//  Created by bin hu on 2025/6/3.
//

import UIKit

// 定义Section枚举作为分组标识符

enum Section: CaseIterable {
    case main
    case secondary
    var headerTitle: String {
        switch self {
        case .main: return "主要数据"
        case .secondary: return "附加数据"
        }
    }
}

// 定义Item结构体作为数据模型
struct Item: Hashable {
    let id = UUID()
    var title: String
}

class ViewController: UIViewController {
    
    private var tableView: UITableView!
    private var dataSource: UITableViewDiffableDataSource<Section, Item>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
        configureDataSource()
        applyInitialSnapshot()
    }
    
    private func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .insetGrouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        view.addSubview(tableView)
    }
    
    private func configureDataSource() {
        dataSource = UITableViewDiffableDataSource(tableView: tableView) {
            (tableView, indexPath, item) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = item.title
            return cell
        }
    }
    
    private func applyInitialSnapshot() {
        var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
        snapshot.appendSections([.main, .secondary])
        
        let mainItems = [Item(title: "第一项"), Item(title: "第二项")]
        let secondaryItems = [Item(title: "附加项A"), Item(title: "附加项B")]
        
        snapshot.appendItems(mainItems, toSection: .main)
        snapshot.appendItems(secondaryItems, toSection: .secondary)
        
        dataSource.apply(snapshot, animatingDifferences: true)
    }
    
}

extension ViewController: UITableViewDelegate {
    // 在UITableViewDelegate中实现滑动删除
    func tableView(_ tableView: UITableView,
                   trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] (_, _, completion) in
            guard let self = self else { return }
            // 1. 获取当前数据标识符
            guard let item = self.dataSource.itemIdentifier(for: indexPath) else {
                return
            }
            
            // 2. 创建新快照并删除
            var newSnapshot = self.dataSource.snapshot()
            newSnapshot.deleteItems([item])
            
            // 3. 可选：检查Section是否为空
            if #available(iOS 15.0, *) {
                guard let section = dataSource.sectionIdentifier(for: indexPath.section) else {
                    return
                }
                if newSnapshot.numberOfItems(inSection: section) == 0 {
                    newSnapshot.deleteSections([section])
                }
            } else {
                // Fallback on earlier versions
            }
            // 4. 应用更新
            self.dataSource.apply(newSnapshot, animatingDifferences: true)
            completion(true)
        }
        return UISwipeActionsConfiguration(actions: [deleteAction])
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 50))
        header.backgroundColor = .systemGroupedBackground
        
        let label = UILabel(frame: CGRect(x: 20, y: 10, width: 200, height: 30))
        label.text = Section.allCases[section].headerTitle
        label.font = .boldSystemFont(ofSize: 18)
        header.addSubview(label)
        
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        let label = UILabel(frame: CGRect(x: 20, y: 0, width: 200, height: 30))
        label.text = "第\(section+1)区结束"
        label.textColor = .gray
        footer.addSubview(label)
        return footer
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        navigationController?.pushViewController(CustomViewController(), animated: true)
    }
    
}

